import pinia, { useUserStore } from '@/store';
import { getSlientInfoApi, getTeacherAllInfoApi, getUserOpenid, OpenIdItem } from '@/service/user';
import { error } from 'console';
import { toAuthPage } from './jump';

const checkSession = () => {
	return new Promise((resolve, reject) => {
		uni.checkSession({
			success() {
				resolve(true);
			},
			fail() {
				reject(false);
			},
		});
	});
};

const getLoginCode = () => {
	return new Promise((resolve, reject) => {
		uni.login({
			provider: 'weixin',
			success(res) {
				if (res.code) {
					resolve(res);
				} else {
					reject(res);
				}
			},
			fail(err) {
				reject(err);
			},
		});
	});
};

const checkLogin = () => {
	const userStore = useUserStore(pinia);
	return new Promise((resolve, reject) => {
		if (userStore.userInfo.session_key) {
			checkSession()
				.then(() => {
					resolve({
						openid: userStore.userInfo.openid,
						session_key: userStore.userInfo.session_key,
						unionid: userStore.userInfo.unionid,
					});
				})
				.catch(() => {
					reject(false);
				});
		} else {
			reject(false);
		}
	});
};

const getOpenId = (showLoading = false) => {
	return new Promise((resolve, reject) => {
		checkLogin()
			.then(loginInfo => {
				resolve(loginInfo);
			})
			.catch(() => {
				getLoginCode()
					.then(async (res: { code: string }) => {
						getSessionKey(res.code, resolve, reject, showLoading);
					})
					.catch(() => {
						if (showLoading) {
							uni.showToast({
								icon: 'none',
								title: '登录失败~',
							});
						}
						reject();
					});
			});
	});
};

const getSessionKey = async (code: string, resolve, reject, showLoading = false) => {
	const userStore = useUserStore(pinia);
	try {
		const data = await getUserOpenid(code);
		if (data.status_code === 200) {
			userStore.setUserInfo({ ...userStore.userInfo, ...data.data });
			resolve(data.data as OpenIdItem);
		} else {
			if (showLoading) {
				uni.showToast({
					icon: 'none',
					title: data.message || '登录失败~',
				});
			}
			reject();
		}
	} catch (error) {
		if (showLoading) {
			uni.showToast({
				icon: 'none',
				title: '登录失败~',
			});
		}
		reject();
	}
};

const getUserSlientInfo = (showLoading = false) => {
	const userStore = useUserStore(pinia);
	return new Promise((resolve, reject) => {
		getLoginCode().then(async (res: { code: string }) => {
			getSlientInfo(res.code, resolve, reject, showLoading)
				.then(async (slientInfo: any) => {
					console.log('=======>getUserSlientInfo', slientInfo);
					if (slientInfo.token.access_token && slientInfo.token.token_type) {
						userStore.setUserInfo({
							...userStore.userInfo,
							token: slientInfo.token.token_type + slientInfo.token.access_token,
						});
						const data = await getTeacherAllInfoApi();
						console.log('=======>getDataInfo', data);
						if (data.status_code === 200) {
							userStore.setUserInfo({ ...userStore.userInfo, ...data.data });
							resolve(userStore.userInfo);
						} else {
							if (showLoading) {
								uni.showToast({
									icon: 'none',
									title: data.message || '登录失败~',
								});
							}
							uni.redirectTo({
								url: '/pages-user/account/add/index',
							});
							reject();
						}
					}
				})
				.catch(() => {
					if (showLoading) {
						uni.showToast({
							icon: 'none',
							title: '登录失败~',
						});
					}
					reject();
				});
		});
	});
};
const getUserInfoByToken = () => {
	const userStore = useUserStore(pinia);
	return new Promise(async (resolve, reject) => {
		const data = await getTeacherAllInfoApi();
		if (data.status_code === 200) {
			userStore.setUserInfo({ ...userStore.userInfo, ...data.data });
			resolve(userStore.userInfo);
		} else {
			uni.showToast({
				icon: 'none',
				title: data.message || '获取用户信息失败',
			});
			reject();
		}
	});
};

const getSlientInfo = (code: string, resolve, reject, showLoading = false) => {
	const userStore = useUserStore(pinia);
	return new Promise(async (resolve, reject) => {
		try {
			const data = await getSlientInfoApi(code);
			console.log('=======>data', data);
			if (data.status_code === 200) {
				// if (!data.data.length) toAuthPage();
				userStore.setUserInfo({ ...userStore.userInfo, ...data.data });
				resolve(data.data as OpenIdItem);
			} else if (data.status_code === 500) {
				uni.showToast({
					icon: 'none',
					title: data.message || '登录失败~',
				});
				toAuthPage();
			} else {
				if (showLoading) {
					uni.showToast({
						icon: 'none',
						title: data.message || '登录失败~',
					});
				}
				reject();
			}
		} catch (error) {
			if (showLoading) {
				uni.showToast({
					icon: 'none',
					title: '登录失败~',
				});
			}
			reject();
		}
	});
};

const getLoginStatus = () => {
	const userStore = useUserStore(pinia);
	if (userStore.userInfo.token && userStore.userInfo.school_id) {
		return true;
	} else {
		return false;
	}
};

export default {
	checkSession,
	getLoginCode,
	checkLogin,
	getOpenId,
	getUserSlientInfo,
	getLoginStatus,
	getUserInfoByToken,
};
